package com.supconit.kqfx.web.fxzf.search.controllers;

import com.supconit.kqfx.web.fxzf.search.entities.*;
import com.supconit.kqfx.web.fxzf.search.services.*;
import hc.base.domains.AjaxMessage;
import hc.base.domains.Pageable;
import hc.base.domains.Pagination;
import hc.business.dic.services.DataDictionaryService;
import hc.mvc.annotations.FormBean;
import hc.safety.manager.SafetyManager;

import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jodd.util.StringUtil;

import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.util.Region;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import com.supconit.honeycomb.business.authorization.entities.Role;
import com.supconit.honeycomb.business.authorization.entities.User;
import com.supconit.honeycomb.business.authorization.services.RoleService;
import com.supconit.honeycomb.business.organization.services.PersonService;
import com.supconit.kqfx.web.analysis.entities.JgZcd;
import com.supconit.kqfx.web.analysis.services.JgZcdService;
import com.supconit.kqfx.web.fxzf.avro.redis.WriteRedisService;
import com.supconit.kqfx.web.fxzf.warn.entities.Config;
import com.supconit.kqfx.web.fxzf.warn.entities.WarnHistory;
import com.supconit.kqfx.web.fxzf.warn.services.ConfigService;
import com.supconit.kqfx.web.fxzf.warn.services.WarnHistoryService;
import com.supconit.kqfx.web.list.entities.BlackList;
import com.supconit.kqfx.web.list.services.BlackListService;
import com.supconit.kqfx.web.util.DictionaryUtil;
import com.supconit.kqfx.web.util.OperateType;
import com.supconit.kqfx.web.util.SysConstants;
import com.supconit.kqfx.web.util.UtilTool;
import com.supconit.kqfx.web.xtgl.entities.ExtPerson;
import com.supconit.kqfx.web.xtgl.services.SystemLogService;

/**
 * 静态称重数据查询
 * 
 * @author JNJ
 * @time 2017年8月25日10:25:36
 * 
 */
@SuppressWarnings("deprecation")
@RequestMapping("/fxzf/static")
@Controller
public class FxzfStaticController {
	private static final String MODULE_CODE = "FXZF_STATIC";

	@Autowired
	private FxzfStaticService fxzfStaticService;

	@Autowired
	private DataDictionaryService dataDictionaryService;

	@Autowired
	private SystemLogService systemLogService;

	@Autowired
	private VehicleInfoService vehicleInfoService;

	@Autowired
	private VehicleService vehicleService;

	private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@Value("${refresh.time}")
	private String refreshTime;

	@Value("${static.imageServer}")
	private String imageServer;

	private transient static final Logger logger = LoggerFactory.getLogger(FxzfStaticController.class);

	private static final Double MODULE_18 = 18d;
	private static final Double MODULE_25 = 25d;
	private static final Double MODULE_31 = 31d;
	private static final Double MODULE_42 = 42d;
	private static final Double MODULE_46 = 46d;
	private static final Double MODULE_49 = 49d;

	/**
	 * 创建FxzfStatic实体类
	 * 
	 * @return
	 */
	@ModelAttribute("fxzfStatic")
	private FxzfStatic getFxzfStatic() {
		FxzfStatic fxzfStatic = new FxzfStatic();
		return fxzfStatic;
	}

	@RequestMapping(value = "list", method = RequestMethod.GET)
	public String display(ModelMap map, @ModelAttribute("fxzfStatic") FxzfStatic condition, HttpServletRequest request) {
		this.systemLogService.log(MODULE_CODE, OperateType.query.getCode(), "过车信息列表", request.getRemoteAddr());
		String ip = request.getLocalAddr();
		logger.info("请求服务器的IP地址：" + ip);
		map.put("ip", ip);
		map.put("imageServer", imageServer);
		map.put("refreshTime", refreshTime);
		return "/fxzf/static/list";
	}

	@ResponseBody
	@RequestMapping(value = "list", method = RequestMethod.POST)
	public Pagination<FxzfStatic> list(Pagination<FxzfStatic> pager, @FormBean(value = "condition", modelCode = "fxzfStatic") FxzfStatic condition) {
		try {
			if (pager.getPageNo() < 1 || pager.getPageSize() < 1 || pager.getPageSize() > Pagination.MAX_PAGE_SIZE)
				return pager;
			fxzfStaticService.findByPager(pager, condition);
			HashMap<String, String> overLoadMap = DictionaryUtil.dictionary("OVERLOADSTATUS", dataDictionaryService);
			HashMap<String, String> colorMap = DictionaryUtil.dictionary("PLATECOLOR", dataDictionaryService);
			for(FxzfStatic fxzf:pager){
				if(fxzf.getLicense()==null){
					fxzf.setLicense("暂无车牌");
				}
				fxzf.setOverStatus(overLoadMap.get(fxzf.getOverLoadStatus()+""));
				if(fxzf.getLicenseColor()!=null){
					fxzf.setLicenseColor(colorMap.get(fxzf.getLicenseColor()));
				}

				Vehicle vehicle = vehicleService.getById(fxzf.getLicense());
				if(vehicle!=null){
					fxzf.setAxisCount(vehicle.getAxis());
				}

			}
			return pager;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		}
		return null;
	}


	@RequestMapping(value = "view", method = RequestMethod.GET)
	public String view(@RequestParam(required = true) String id, ModelMap model, HttpServletRequest request) {
		FxzfStatic fxzfStatic = this.fxzfStaticService.getById(id);
		if(fxzfStatic.getWeightStand() == null) {
			switch (fxzfStatic.getAxisCount()) {
				case 2:
					fxzfStatic.setWeightStand(MODULE_18);
					break;
				case 3:
					fxzfStatic.setWeightStand(MODULE_25);
					break;
				case 4:
					fxzfStatic.setWeightStand(MODULE_31);
					break;
				case 5:
					fxzfStatic.setWeightStand(MODULE_42);
					break;
				case 6:
					fxzfStatic.setWeightStand(MODULE_46);
					break;
				default:
					fxzfStatic.setWeightStand(MODULE_49);
			}
		}
		model.put("fxzf", fxzfStatic);
		model.put("imageServer", imageServer);
		return "/fxzf/static/view";
	}


	@RequestMapping(value = "edit", method = RequestMethod.GET)
	public String editGet(String id, ModelMap model) {
		FxzfStatic fxzfStatic = this.fxzfStaticService.getById(id);
		if(fxzfStatic.getLicense()==null){
			fxzfStatic.setLicense("暂无车牌");
		}
		if(fxzfStatic.getCaptureTime()!=null){
			fxzfStatic.setTimeStr(format.format(fxzfStatic.getCaptureTime()));
		}

		VehicleInfo vehicleInfo = vehicleInfoService.getByPlaneNo(fxzfStatic.getLicense());
		if(vehicleInfo!=null){
			YhInfo yhInfo = vehicleInfo.getYhInfo();
			fxzfStatic.setYhName(yhInfo.getYhName());
			fxzfStatic.setYhNo(yhInfo.getBusinessLicenseNo());
		}

		Vehicle vehicle = vehicleService.getById(fxzfStatic.getLicense());
		if(vehicle!=null){
			fxzfStatic.setAxisCount(vehicle.getAxis());
		}
		//weightStand overLoad overLoadPercent weight
		if(fxzfStatic.getWeightStand() == null) {
			switch (fxzfStatic.getAxisCount()) {
				case -1:
					fxzfStatic.setWeightStand(MODULE_18);
					break;
				case 2:
					fxzfStatic.setWeightStand(MODULE_18);
					break;
				case 3:
					fxzfStatic.setWeightStand(MODULE_25);
					break;
				case 4:
					fxzfStatic.setWeightStand(MODULE_31);
					break;
				case 5:
					fxzfStatic.setWeightStand(MODULE_42);
					break;
				case 6:
					fxzfStatic.setWeightStand(MODULE_46);
					break;
				default:
					fxzfStatic.setWeightStand(MODULE_49);
			}
		}
		Double weight = fxzfStatic.getWeight();
		Double weightStand = fxzfStatic.getWeightStand() != null ? fxzfStatic.getWeightStand() : 0.0;
		Double overload = weight - weightStand;
		DecimalFormat dFormat = new DecimalFormat("#.00");
		if(overload <= 0.0){
			fxzfStatic.setOverLoad(0.00d);
			fxzfStatic.setOverLoadPercent(0.00d);
		}else {
//			fxzfStatic.setOverLoad(Double.valueOf(dFormat.format(overload)));
//			Double overloadPercent = overload / weightStand;
//			fxzfStatic.setOverLoadPercent(Double.valueOf(dFormat.format(overloadPercent)));
			fxzfStatic.setOverLoad(fxzfStatic.getOverLoad());
			fxzfStatic.setOverLoadPercent(fxzfStatic.getOverLoadPercent());
		}

		model.put("axisnum", fxzfStatic.getAxisCount());
		model.put("fxzf", fxzfStatic);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		model.put("nowTime",format.format(new Date()));
		model.put("imageServer", imageServer);
		model.put("picAddr",fxzfStatic.getCarPicdir());
		return "/fxzf/static/edit";
	}

	@RequestMapping(value = "edit-readonly", method = RequestMethod.GET)
	public String editReadonly(String id, ModelMap model) {
		FxzfStatic fxzfStatic = this.fxzfStaticService.getById(id);
		if(fxzfStatic.getLicense()==null){
			fxzfStatic.setLicense("暂无车牌");
		}
		if(fxzfStatic.getCaptureTime()!=null){
			fxzfStatic.setTimeStr(format.format(fxzfStatic.getCaptureTime()));
		}

		VehicleInfo vehicleInfo = vehicleInfoService.getByPlaneNo(fxzfStatic.getLicense());
		if(vehicleInfo!=null){
			YhInfo yhInfo = vehicleInfo.getYhInfo();
			fxzfStatic.setYhName(yhInfo.getYhName());
			fxzfStatic.setYhNo(yhInfo.getBusinessLicenseNo());
		}

		Vehicle vehicle = vehicleService.getById(fxzfStatic.getLicense());
		if(vehicle!=null){
			fxzfStatic.setAxisCount(vehicle.getAxis());
		}
		if(fxzfStatic.getWeightStand() == null) {
			switch (fxzfStatic.getAxisCount()) {
				case -1:
					fxzfStatic.setWeightStand(MODULE_18);
					break;
				case 2:
					fxzfStatic.setWeightStand(MODULE_18);
					break;
				case 3:
					fxzfStatic.setWeightStand(MODULE_25);
					break;
				case 4:
					fxzfStatic.setWeightStand(MODULE_31);
					break;
				case 5:
					fxzfStatic.setWeightStand(MODULE_42);
					break;
				case 6:
					fxzfStatic.setWeightStand(MODULE_46);
					break;
				default:
					fxzfStatic.setWeightStand(MODULE_49);
			}
		}
		Double weight = fxzfStatic.getWeight();
		Double weightStand = fxzfStatic.getWeightStand() != null ? fxzfStatic.getWeightStand() : 0.0;
		Double overload = weight - weightStand;
		DecimalFormat dFormat = new DecimalFormat("#.00");
		if(overload <= 0.0){
			fxzfStatic.setOverLoad(0.00d);
			fxzfStatic.setOverLoadPercent(0.00d);
		}else {
			fxzfStatic.setOverLoad(fxzfStatic.getOverLoad());
			fxzfStatic.setOverLoadPercent(fxzfStatic.getOverLoadPercent());
		}

		model.put("axisnum", fxzfStatic.getAxisCount());
		model.put("fxzf", fxzfStatic);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		model.put("nowTime",format.format(new Date()));
		model.put("imageServer", imageServer);
		model.put("picAddr",fxzfStatic.getCarPicdir());
		return "/fxzf/static/edit_readonly";
	}

	@ResponseBody
	@RequestMapping(value = "edit", method = RequestMethod.POST)
	public AjaxMessage editPost(@FormBean(value = "fxzf", modelCode = "fxzfStatic") FxzfStatic condition) {
		try{
			fxzfStaticService.update(condition);
			return AjaxMessage.success();
		}catch (Exception e){
			e.printStackTrace();
		}
		return AjaxMessage.error("");
	}

	@ResponseBody
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	public AjaxMessage deletePost(String id) {
		try{
			if(id!=null){
				fxzfStaticService.deleteById(id);
				return AjaxMessage.success();
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return AjaxMessage.error("");
	}

	/**
	 * 获取治超站数据
	 *
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "detectStation", method = RequestMethod.POST)
	AjaxMessage getDetectionStation() {
		HashMap<String, String> stationMap = DictionaryUtil.dictionary("DETECTIONSTATION", dataDictionaryService);
		List<String> stationList = new ArrayList<String>();
		for (String key : stationMap.keySet()) {
			stationList.add(key + ":" + stationMap.get(key));
		}
		return AjaxMessage.success(stationList);
	}


	@RequestMapping(value = "exportPage", method = RequestMethod.GET)
	public void exportExcel(HttpServletRequest request, HttpServletResponse response, String pageNo, @FormBean(value = "condition", modelCode = "fxzfStatic") FxzfStatic condition) {
		logger.info("-------------------------导出本页excel列表---------------");
		try {
			if (condition.getLicense() != null) {
				condition.setLicense(java.net.URLDecoder.decode(condition.getLicense(), "utf-8"));
			}
			Pagination<FxzfStatic> pager = new Pagination<FxzfStatic>();
			pager.setPageNo(Integer.valueOf(pageNo));
			pager.setPageSize(15);
			Pageable<FxzfStatic> page = (Pagination<FxzfStatic>) fxzfStaticService.findByPager(pager, condition);
			SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
			Date date = new Date();
			String time = formatter.format(date);
			String title = "称重数据_" + time + ".xls";
			editExcel(page, response, title);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@RequestMapping(value = "exportAll", method = RequestMethod.GET)
	public void exportAll(HttpServletRequest request, HttpServletResponse response, String total, @FormBean(value = "condition", modelCode = "FxzfStatic") FxzfStatic condition) {
		logger.info("-------------------------导出全部excel列表---------------");
		try {

			Pagination<FxzfStatic> pager = new Pagination<FxzfStatic>();
			pager.setPageNo(1);
			pager.setPageSize(Integer.MAX_VALUE);
			Pageable<FxzfStatic> page = (Pagination<FxzfStatic>) fxzfStaticService.findByPager(pager, condition);
			SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
			Date date = new Date();
			String time = formatter.format(date);
			String title = "称重数据_" + time + ".xls";
			editExcel(page, response, title);
		} catch (Exception e) {
			logger.info("-------------------------导出全部excel列表---------------");
		}

	}

	HSSFCellStyle setHSSFCellStyle(HSSFCellStyle style) {
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		return style;
	}

	void editExcel(Pageable<FxzfStatic> pager, HttpServletResponse response, String title) {
		OutputStream out = null;
		try {
			response.setHeader("Content-Disposition", "attachment; filename=" + new String(title.getBytes("GB2312"), "iso8859-1"));
			response.setContentType("application/msexcel;charset=UTF-8");
			out = response.getOutputStream();
			HSSFWorkbook workbook = new HSSFWorkbook();
			HSSFSheet sheet = workbook.createSheet(UtilTool.toGBK("称重数据"));
			HSSFRow top = sheet.createRow(0);
			HSSFRow row = sheet.createRow(1);
			HSSFCellStyle style1 = workbook.createCellStyle();
			HSSFCellStyle style2 = workbook.createCellStyle();
			HSSFCellStyle style3 = workbook.createCellStyle();

			/**************************************** 字体font *********************/
			HSSFFont font1 = workbook.createFont();
			font1.setColor(HSSFColor.BLACK.index);
			font1.setFontHeightInPoints((short) 10);
			font1.setBoldweight((short) 24);
			font1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
			HSSFFont font2 = workbook.createFont();
			font2.setColor(HSSFColor.BLACK.index);
			font2.setFontHeightInPoints((short) 10);
			font2.setBoldweight((short) 24);

			style1.setFont(font1);
			style1 = setHSSFCellStyle(style1);
			style1.setFillBackgroundColor(HSSFColor.AQUA.index);
			style1.setFillForegroundColor(HSSFColor.AQUA.index);
			style1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

			style2.setFont(font2);
			style2 = setHSSFCellStyle(style2);

			style3.setFont(font1);
			style3 = setHSSFCellStyle(style3);

			/** 字体居中 **/
			style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			style3.setAlignment(HSSFCellStyle.ALIGN_CENTER);

			// 设置表头长度
			for (int i = 0; i < 7; i++) {
				HSSFCell cell = top.createCell(i);
				cell.setCellStyle(style3);
			}
			// 设置表头长度
			top.getSheet().addMergedRegion(new Region(0, (short) 0, 0, (short) 7));
			HSSFCell celltop = top.createCell(0);
			celltop.setCellValue("称重数据");
			celltop.setCellStyle(style3);

			HashMap<String, String> detectionMap = DictionaryUtil.dictionary("DETECTIONSTATION", dataDictionaryService);
			HashMap<String, String> punishMap = DictionaryUtil.dictionary("OVERLOADPUNISH", dataDictionaryService);
			HashMap<String, String> overLoadMap = DictionaryUtil.dictionary("OVERLOADSTATUS", dataDictionaryService);

			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			String[] head = { "序号", "称重时间", "车牌号", "总重(吨)", "超重(吨)","超限率(%)", "轴数", "超限等级",};
			int i0 = 0, i1 = 0, i2 = 0, i3 = 0, i4 = 0, i5 = 0, i6 = 0, i7 = 0;
			for (int i = 0; i < head.length; i++) {
				HSSFCell cell = row.createCell(i);
				cell.setCellValue(head[i]);
				cell.setCellStyle(style1);
				if (i == 0) {
					i0 = head[i].length() * 256 + 256 * 10;
				}
				if (i == 1) {
					i1 = head[i].length() * 256 + 256 * 20;
				}
				if (i == 2) {
					i2 = head[i].length() * 256 + 256 * 10;
				}
				if (i == 3) {
					i3 = head[i].length() * 256 + 256 * 10;
				}
				if (i == 4) {
					i4 = head[i].length() * 256 + 256 * 10;
				}
				if (i == 5) {
					i5 = head[i].length() * 256 + 256 * 10;
				}
				if (i == 6) {
					i6 = head[i].length() * 256 + 256 * 10;
				}
				if (i == 7) {
					i7 = head[i].length() * 256 + 256 * 10;
				}
			}

			for (int i = 0; i < pager.size(); i++) {
				row = sheet.createRow(i + 2);
				// 序号
				HSSFCell cell0 = row.createCell(0);
				cell0.setCellValue(1 + i);
				cell0.setCellStyle(style2);
				if (String.valueOf(1 + i).length() * 256 >= i0) {
					i0 = String.valueOf(1 + i).length() * 256 + 256 * 8;
				}

				//过车时间
				HSSFCell cell1 = row.createCell(1);
				cell1.setCellStyle(style2);
				if (pager.get(i).getCaptureTime() != null) {
					cell1.setCellValue(format.format(pager.get(i).getCaptureTime()));
					if (format.format(pager.get(i).getCaptureTime()).length() * 356 >= i1) {
						i1 = format.format(pager.get(i).getCaptureTime()).length() * 356 + 356 * 10;
					}
				} else {
					cell1.setCellValue("");
				}
				//车牌号
				HSSFCell cell2 = row.createCell(2);
				cell2.setCellStyle(style2);
				if (pager.get(i).getLicense() != null) {
					cell2.setCellValue(pager.get(i).getLicense());
					if (pager.get(i).getLicense().length() * 256 >= i2) {
						i2 = pager.get(i).getLicense().length() * 256 + 256 * 10;
					}
				} else {
					cell2.setCellValue("");
				}
				//总重
				HSSFCell cell3 = row.createCell(3);
				cell3.setCellStyle(style2);
				if (pager.get(i).getWeight() != null) {
					cell3.setCellValue(pager.get(i).getWeight());
				} else {
					cell3.setCellValue("");
				}
				// 超重（吨）
				HSSFCell cell4 = row.createCell(4);
				cell4.setCellStyle(style2);
				if (pager.get(i).getOverLoad() != null) {
					cell4.setCellValue(pager.get(i).getOverLoad());
				} else {
					cell4.setCellValue("");
				}
				// 超限率
				HSSFCell cell5 = row.createCell(5);
				cell5.setCellStyle(style2);
				if (pager.get(i).getOverLoadPercent() != null) {
					cell5.setCellValue(pager.get(i).getOverLoadPercent());
				} else {
					cell5.setCellValue("");
				}
				// 轴数
				HSSFCell cell6 = row.createCell(6);
				cell6.setCellStyle(style2);
				if (pager.get(i).getAxisCount() != null) {
					cell6.setCellValue(pager.get(i).getAxisCount() + "轴");
				} else {
					cell6.setCellValue("");
				}
				// 超限等级
				pager.get(i).setOverStatus(overLoadMap.get(pager.get(i).getOverLoadStatus()+""));
				String status = pager.get(i).getOverStatus();
				HSSFCell cell7 = row.createCell(7);
				cell7.setCellStyle(style2);
				if (status != null) {
					cell7.setCellValue(status);
					if (status.length() * 256 >= i7) {
						i7 = status.length() * 256 + 256 * 8;
					}
				} else {
					cell7.setCellValue("");
				}
			}
			sheet.setColumnWidth(0, i0);
			sheet.setColumnWidth(1, i1);
			sheet.setColumnWidth(2, i2);
			sheet.setColumnWidth(3, i3);
			sheet.setColumnWidth(4, i4);
			sheet.setColumnWidth(5, i5);
			sheet.setColumnWidth(6, i6);
			sheet.setColumnWidth(7, i7);
			workbook.write(out);
			out.flush();
			out.close();
		} catch (Exception e) {
			logger.error("---------------数据导出失败--------");
			e.printStackTrace();
		}
	}


}
